package com.study.lease.web.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.study.lease.common.constant.RedisConstant;
import com.study.lease.common.exception.LeaseException;
import com.study.lease.common.result.ResultCodeEnum;
import com.study.lease.common.utils.JwtUtil;
import com.study.lease.model.entity.SystemUser;
import com.study.lease.model.enums.BaseStatus;
import com.study.lease.web.admin.mapper.SystemUserMapper;
import com.study.lease.web.admin.service.LoginService;
import com.study.lease.web.admin.vo.login.CaptchaVo;
import com.study.lease.web.admin.vo.login.LoginVo;
import com.study.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.wf.captcha.SpecCaptcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.ibatis.cache.decorators.ScheduledCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SystemUserMapper systemUserMapper;

    @Override
    public CaptchaVo getCaptcha() {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        String code = specCaptcha.text().toLowerCase();
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();
        redisTemplate.opsForValue().set(key, code , RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
        CaptchaVo captchaVo = new CaptchaVo(specCaptcha.toBase64(), key);
        return captchaVo;
    }

    @Override
    public String login(LoginVo loginVo) {
        // 判断是否输入了验证码
       /* if (loginVo.getCaptchaKey()==null){
            //抛出自定义异常
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND.getCode(), ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND.getMessage());
        }*/
        if (!StringUtils.hasText(loginVo.getCaptchaCode())) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND.getCode(), ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND.getMessage());
        }
        // 判断验证码是否过期
        String code =redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if (code==null){
            throw  new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED.getCode(),ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED.getMessage());

        }
        //比较验证码是否正确
        if(!code.equals(loginVo.getCaptchaCode())){
            throw  new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR.getCode(),ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR.getMessage());
        }
        //验证用户名是否存在
        /**
         * 这里不使用 queryWrapper，因为queryWrapper会自动添加一个select * ，而数据库中密码是加密的，所以会报错
         * 必须要自己创建sql语句
         */
       /* LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUser::getUsername, loginVo.getUsername());*/
        SystemUser systemUser = systemUserMapper.selectOneByUsername(loginVo.getUsername());
        if (systemUser==null){
            throw  new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR.getCode(),ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR.getMessage());
        }
        //判断用户名是否被禁
        if (systemUser.getStatus()== BaseStatus.DISABLE){
            throw  new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR.getCode(),ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR.getMessage());
        }
        /**
         * 在数据库中密码是加密的，所以这里需要先将密码进行加密，再进行比较
         */
        //校验用户名和密码
        if (!systemUser.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword()))){
            throw  new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR.getCode(),ResultCodeEnum.ADMIN_ACCOUNT_ERROR.getMessage());
        }


        return JwtUtil.createToken(systemUser.getId(),systemUser.getUsername());
    }

    @Override
    public SystemUserInfoVo getLoginUserInfoById(Long userId) {
        SystemUser systemUser = systemUserMapper.selectById(userId);
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        systemUserInfoVo.setName(systemUser.getName());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        return systemUserInfoVo;
    }
}
